# -*- encoding: utf-8 -*-

from Common.mysql import db
from Common.public_method import utc_8
from src.ApiTest.SqlData.Database.sql_database import SqlData, SqlSchema
from sqlalchemy.exc import SQLAlchemyError
from Common.yaml_method import YamlMethod


class UpdateSql:
    """
    更新SQL配置信息接口
    """

    @staticmethod
    def update_sql(config_id, config_name, project_id, project_name, database_type, function_name, sql_data, pre_parameter,
                   after_parameter, update_user):
        """
        更新SQL配置信息
        :param config_id:
        :param config_name: 配置名称
        :param project_id: 项目ID
        :param project_name: 项目名称
        :param database_type: 数据库类型
        :param function_name: 运行方法
        :param sql_data: 运行sql
        :param pre_parameter: 前置参数
        :param after_parameter: 数据提取
        :param update_user: 更新人
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        update_time = utc_8()

        info = SqlData.query.filter_by(id=config_id).first()

        if info:
            info.configName = config_name
            info.projectId = project_id
            info.projectName = project_name
            info.databaseType = database_type
            info.functionName = function_name
            info.sqlData = sql_data
            info.pre_parameter = pre_parameter
            info.after_parameter = after_parameter
            info.update_time = update_time
            info.update_user = update_user

            try:
                db.session.commit()
            except SQLAlchemyError:
                db.session.rollback()
                res = {
                    'code': code[6],
                    'data': [],
                    'message': 'SQL信息更新失败'
                }
                return res

            res = {
                'code': code[0],
                'data': [],
                'message': 'SQL信息更新成功'
            }
            return res
        else:
            res = {
                'code': code[3],
                'data': [],
                'message': 'SQL信息不存在'
            }
            return res
